<?php

namespace App\Http\Controllers;

use App\Helpers\libs\BaiDuPan;
use App\Models\Code;
use App\Models\Link;
use App\Models\Resource;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class BaiDuPanController extends Controller
{
    public function index(Request $request)
    {
        return view('home');
    }

    public function analysis(Request $request)
    {
        if (config('pan.showCode')) {
            $code = $request->get('code', '');
            $c = Code::where('status', 1)->where('code', $code)->first();
            if (empty($c)) {
                $error = '激活码无效，请更换激活码';
                return view('error', compact(
                    'error'
                ));
            }
            if ($c['num'] != -1) {
                if ($c['num'] == 0) {
                    $error = '激活码无效，请更换激活码';
                    return view('error', compact(
                        'error'
                    ));
                }
                $c['num'] -= 1;
            }
            $c['count'] += 1;
            $c->save();
        }
        $pan = new BaiDuPan();

        $url = $request->get('url', '');
        $pwd = $request->get('pwd', '');
        $path = $request->get('path', '');
        if (empty($path)) {
            $router = [
                'name' => '全部文件',
                'path' => $request->fullUrl()
            ];
            $routers = [$router];
            session(['routers' => json_encode($routers)]);
            if (strpos($url, 'pan.baidu.com') === false) {
                $error = '无效的分享链接';
                return view('error', compact(
                    'error'
                ));
            } else {
                try {
                    $sid = $pan->getSid($url);
                    $lnd = $pan->getBdLND($sid, $pwd);
                    Log::info($lnd);
                    $result = $pan->getAnalysis($sid, $lnd);
                    if ($result['errno'] == -1) {
                        $error = '请确认提取码是否有问题，若提取码无误，请联系管理员';
                        return view('error', compact(
                            'error'
                        ));
                    }
                    if ($result['errno'] == -2) {
                        $error = '解析脚本有问题，请联系管理员';
                        return view('error', compact(
                            'error'
                        ));
                    }
                    // Log::info($result);
                    $items = $result['file_list'];
                    $shareId = $result['shareid'];
                    $uk = $result['share_uk'];
                    session([
                        'shareId' => $shareId,
                        'uk' => $uk,
                        'sid' => $sid,
                        'lnd' => $lnd,
                        'bdstoken' => $result['bdstoken'],
                    ]);
                    if (count($items) > 0) {
                        $rs = Resource::where('url', $url)->first();
                        if (empty($rs)) {
                            $rs = new Resource();
                            $rs['url'] = $url;
                            $rs['pwd'] = $pwd;
                            $rs['title'] = $items[0]['server_filename'];
                            $rs->save();
                        } else {
                            if ($rs['pwd'] != $pwd) {
                                $rs['pwd'] = $pwd;
                                $rs->save();
                            }
                        }
                    }
                } catch (\Exception $exception) {
                    Log::info($exception);
                    $error = '解析出错，请确认提取码是否正确';
                    return view('error', compact(
                        'error'
                    ));
                }

            }
        } else {

            $shareId = session('shareId');
            $uk = session('uk');
            $lnd = session('lnd');
            if (empty($shareId) || empty($uk)) {
                Log::info('+++++++++++++++++++++++++++++++++++++++++++++');
                Log::info('shareId:' . $shareId);
                Log::info('uk:' . $uk);
                Log::info('lnd:' . $lnd);
                $error = '文件夹加载失败';
                return view('error', compact(
                    'error'
                ));
            }

            $path = $request->get('path', '');

            $urls = json_decode(session('routers'));
            $nowUrl = $request->fullUrl();
            $routers = [];
            $flag = true;
            foreach ($urls as $u) {
                $router = $u;
                $routers[] = $router;
                if ($u->path == $nowUrl) {
                    $flag = false;
                    break;
                }
            }
            if ($flag) {
                $params = explode('/', $path);
                $routers[] = [
                    'name' => $params[count($params) - 1],
                    'path' => $nowUrl,
                ];
            }
            session(['routers' => json_encode($routers)]);

            $result = $pan->getDirFiles($path, $lnd, $shareId, $uk);
            $items = $result['list'];
        }

        $files = [];
        foreach ($items as $item) {
            $file = $item;
            if ($item['isdir'] == 0) {
                $arr = explode('.', $item['server_filename']);
                if (count($arr) > 0) {
                    $suffix = $arr[count($arr) - 1];
                } else {
                    $suffix = '未知文件格式';
                }
                $file['suffix'] = $suffix;
            }
            $files[] = $file;
        }
        $routers = json_decode(session('routers'));

        return view('dir', compact(
            'files',
            'routers',
        ));
    }

    public function download(Request $request)
    {
        $shareId = session('shareId');
        $uk = session('uk');
        $lnd = session('lnd');
        $bdSToken = session('bdstoken');
        if (empty($shareId) || empty($uk)) {
            $error = '下载链接解析失败，请联系管理员';
            return view('error', compact(
                'error'
            ));
        }

        $sid = session('sid');
        $fsId = $request->get('fsId');

        $pan = new BaiDuPan();
        $result = $pan->getSign($sid, $lnd);

        // TODO result需要进行errno字段判断，错误处理

        $sign = $result["data"]["sign"];
        $timestamp = $result["data"]["timestamp"];

        $link = $pan->getDownLink(
            $fsId, $timestamp, $sign, $lnd, $shareId,
            $uk, $bdSToken, false
        );
        $file = $link['list'][0];
        Log::info($file);
        $smallFile = (int)$file['size'] < 52428800;
        $result = $pan->getRealLink($file['dlink'], $smallFile);

        $db = Link::where('filename', $file['server_filename'])
            ->where('md5', $file['md5'])
            ->where('path', $file['path'])
            ->first();

        if (empty($db)) {
            $db = new Link();
            $db['filename'] = $file['server_filename'];
            $db['size'] = $file['size'];
            $db['md5'] = $file['md5'];
            $db['path'] = $file['path'];
            $db['server_ctime'] = $file['server_ctime'];
        }
        $db['dlink'] = $file['dlink'];
        $db['real_link'] = 'https://' . $result;
        $db->save();

        return view('down', compact(
            'link',
            'file',
            'result'
        ));
    }
}
